package org.redrock.test.interceptor.impl;

import com.google.gson.Gson;
import org.redrock.test.bean.RequestInfo;
import org.redrock.test.config.WeixinConfig;
import org.redrock.test.interceptor.BaseInterceptor;
import org.redrock.test.interceptor.bean.SnsapiBase;
import org.redrock.test.interceptor.bean.SnsapiUserinfo;
import org.redrock.test.repository.NetworkRepository;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class SnsapiUserinfoAuth implements BaseInterceptor{

    private WeixinConfig weixinConfig;
    private NetworkRepository networkRepository = new NetworkRepository();
    private String key = SnsapiBase.class.toString();
    private String getCodeApiFormat = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    private String getOpenidApiFormat = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";
    private String getUserinfoApiFormat = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    @Override
    public boolean interceptor(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        if (httpServletRequest.getSession().getAttribute(key) != null) {
            return true;
        }
        String code = httpServletRequest.getParameter("code");
        if (!StringUtils.isEmpty(code)) {
            String getOpenidUrl = String.format(getOpenidApiFormat, weixinConfig.getAppId(), weixinConfig.getSecret(), code);
            RequestInfo requestInfo = new RequestInfo(
                    "get",
                    getOpenidUrl
            );
            String data = networkRepository.curl(requestInfo);
            Gson gson = new Gson();
            SnsapiBase snsapiBase = gson.fromJson(data, SnsapiBase.class);
            if (ObjectUtils.isEmpty(snsapiBase)) {
                //...
                return false;
            }
            String getUserinfoApi = String.format(getUserinfoApiFormat, snsapiBase.getAccess_token(), snsapiBase.getOpenid());
            requestInfo.setUrl(getUserinfoApi);
            data = networkRepository.curl(requestInfo);
            SnsapiUserinfo snsapiUserinfo = gson.fromJson(data, SnsapiUserinfo.class);
            httpServletRequest.setAttribute(key, snsapiUserinfo);
            httpServletRequest.getSession().setAttribute(key, snsapiUserinfo);
            return true;
        }
        String redirectUrl = URLEncoder.encode(weixinConfig.getRedirect() + httpServletRequest.getRequestURI(), "UTF-8");
        String getCodeUrl = String.format(getCodeApiFormat, weixinConfig.getAppId(), redirectUrl);
        httpServletResponse.sendRedirect(getCodeUrl);
        return false;
    }
}